var router = require('express').Router();


var DBManager = require("../tools/DBManage");
var defaultInfo = require("../tools/default");

//建表
DBManager.createTableNews();

//router.get('/', function(req, res) {
//res.send("aaa");
//});
////对news操作的相关接口
//router.get("/getAllNews",function(req,res){
//	console.log(req.body);
//	var result = dbM.searchAllNews();
//	res.send(result);
//})


//发布的接口
router.post(defaultInfo.ADD_NEWS,function(req,res){
	//得到请求参数
	var body = req.body;
	
	
//	{ des: '12',
//	  endTime: '-2177477940000',
//	  lat: '28.21347823',
//	  log: '112.97935279',
//	  price: '12',
//	  startTime: '1504676118709',
//	  time: '1900-12-31T17:01:00.000Z',
//	  type: '跑腿' }

	if (body.type&&body.userID&&body.des&&body.startTime&&body.endTime&&body.price&&body.lat&&body.log){
//		console.log(body);
//      DBManager.addNews([body.type,body.userID,body.des,body.startTime,body.endTime,body.lat,body.log])
        DBManager.addNews([parseInt(body.type),parseInt(body.userID),body.des,parseInt(body.startTime),parseInt(body.endTime),parseInt(body.price),parseFloat(body.lat),parseFloat(body.log)])
        .then(function () {
            res.send(defaultInfo.NEWS_ADD_SUCCESS);
        }).catch(function (error) {
        	
        	console.log(error);
            res.send(defaultInfo.ERROR_NEWS_ADD_FAIL);
        });

    }else {
        res.send(defaultInfo.ERROR_NOT_VALIDITY_PARAM);
    }
})



//查询所有发布内容的接口
router.get(defaultInfo.SEARCH_ALL_NEWS,function(req,res){
	DBManager.searchAllNews()
	.then(function(result){
		//查询成功
		//1、有数据
		//2、没有数据
		console.log(result);
		defaultInfo.NEWS_SEARCH_SUCCESS.data = result;
		result.length?res.send(defaultInfo.NEWS_SEARCH_SUCCESS):res.send(defaultInfo.ERROR_NEWS_SEARCH_FAIL);
		
		
	})
	.catch(function(error){
		defaultInfo.ERROR_NEWS_SEARCH_FAIL.message = error.message;
		res.send(defaultInfo.ERROR_NEWS_SEARCH_FAIL);
	})
});


module.exports = router;

